package com.jzo2o.trade.service.impl;

import com.jzo2o.api.trade.dto.response.ExecutionResultResDTO;
import com.jzo2o.api.trade.enums.PayChannelEnum;
import com.jzo2o.trade.model.domain.RefundRecord;
import com.jzo2o.trade.service.IAliRefundService;
import com.jzo2o.trade.service.IRefundRecordService;
import com.jzo2o.trade.service.IRefundService;
import com.jzo2o.trade.service.IWxRefundService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * \* User: chy
 * \* Date: 2025/10/9  9:25
 * \* Description:
 * \
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class RefundServiceImpl implements IRefundService {

    private final IRefundRecordService refundRecordService;
    private final IWxRefundService wxRefundService;
    private final IAliRefundService aliRefundService;

    /**
     * 统一收单交易退款接口
     * 当交易发生之后一段时间内，由于买家或者卖商品的原因需要退款时，卖家可以通过退款接口将支付款退还给买家，
     * 在收到退款请求并且验证成功之后，按照退款规则将支付款按原路退到买家帐号上。
     *
     * @param tradingOrderNo 支付单号
     * @param refundAmount   退款金额
     * @return
     */
    @Override
    public ExecutionResultResDTO refundTrading(Long tradingOrderNo, BigDecimal refundAmount) {
        log.info("统一收单交易退款接口开始执行,订单单号为:{}", tradingOrderNo);
        // 1.创建退款记录表
        RefundRecord refundRecord = refundRecordService.saveRefundRecord(tradingOrderNo, refundAmount);

        // 2.调用第三方退款平台
        ExecutionResultResDTO executionResultResDTO = null;
        // wx支付
        if (refundRecord.getTradingChannel().equals(PayChannelEnum.WECHAT_PAY.getValue())) {
            log.info("微信退款开始");
            executionResultResDTO  = wxRefundService.refund(refundRecord);
        // 支付宝 支付
        }else if(refundRecord.getTradingChannel().equals(PayChannelEnum.ALI_PAY.getValue())){
            log.info("支付宝退款开始");
            executionResultResDTO =  aliRefundService.refund(refundRecord);

        }

        // 3.更新退款记录表
        // 退款状态
        refundRecord.setRefundStatus(executionResultResDTO.getRefundStatus());
        // 第三方退款单号
        refundRecord.setRefundId(executionResultResDTO.getRefundId());
        // 退款结果
        refundRecordService.updateById(refundRecord);

        // 4.通知订单服务

        return executionResultResDTO;
    }
}
